<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户抽奖机会总表
 */

class AnswerActivityUserPrize extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_prize';


    /**
     * 获取用户是否还有抽奖机会
     * @param act_id 活动id
     * @param user_guid 用户guid
     */
    public function isHavePrizeNumber($act_id , $user_guid){
        $res = $this->select('number' , 'use_number')->where('act_id', $act_id)->where('user_guid', $user_guid)->first();

        return $res && $res['number'] > $res['use_number'] ? true : false ;
    }

    /**
     * 获取用户现有钥匙个数
     * @param act_id 活动id
     * @param user_guid 用户guid
     */
    public function getUserPrizeNumber($act_id , $user_guid){
        $res = $this->select('number' , 'use_number')->where('act_id', $act_id)->where('user_guid', $user_guid)->first();

        return $res;
    }

    /**
     * 添加一把钥匙
     * @param act_id 活动id
     * @param user_guid 用户guid
     */
    public function addUserPrize($act_id , $user_guid){
        $res = $this->where('act_id', $act_id)->where('user_guid', $user_guid)->first();
        if($res){
            $res->number = $res->number + 1;
            return $res->save();
        }
        $this->act_id = $act_id;
        $this->user_guid = $user_guid;
        $this->number = 1;
        $this->use_number = 0;
        return $this->save();
    }


}
